// 封装http请求
import axios from 'axios';
import { CODEMESSAGE } from './error-code';
import { notification } from 'ant-design-vue';
import { getToken } from '@/utils/cache';
import { useStore } from '@/store'
import { getJSCurrTime } from '@/utils/time'
import { getRandomCode } from '@/utils/num'
const service = axios.create({
    baseURL: import.meta.env.YY_API_BASE_URL,
    timeout: Number(import.meta.env.YY_API_TIME_OUT),
    headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// 请求拦截
service.interceptors.request.use((config:any) => {
    config.headers['Authorization'] = 'Bearer ' + getToken() ;
    config.headers['jktranstionid'] = `Q-${useStore().state.user.company?useStore().state.user.company.compCode:'0'}-${useStore().state.user.user?useStore().state.user.user.id:'0'}-${getJSCurrTime()}-${getRandomCode(5)}`
    if (config.method === 'get' && config.params) {
        let url = config.url + '?';
        for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            var part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof (value) !== "undefined") {
                if (typeof value === 'object') {
                    for (const key of Object.keys(value)) {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        url += subPart + encodeURIComponent(value[key]) + "&";
                    }
                } else {
                    url += part + encodeURIComponent(value) + "&";
                }
            }
        }
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

service.interceptors.response.use((res: any) => {
    // hideLoading()
    // 未设置状态码则默认成功状态
    // console.log('res',res)
    // const code = res.data['code'] || 200;
    // // 获取错误信息
    // const msg = CODEMESSAGE[code] || res.data['msg'] || ''
    // if(code === 200){

    // }else{
    //     notification.error({
    //         message: '请求出错',
    //         description: msg
    //     })
    //     return Promise.reject(res.data)
    // }
    return Promise.resolve(res.data)
},
    error => {
        console.log('err' + error)
        // hideLoading()
        let { message } = error;
        if (message == "Network Error") {
            message = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        }
        else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        notification.error({
            message: '请求异常',
            description: message,
            duration: 2
        })
        return Promise.reject(error)
    }
)

export default service;